﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Cinchoo.Core.IO;
using Cinchoo.Core.Collections;
using System.IO;
using System.Collections;
using System.Data.SqlClient;
using System.Threading;
using System.Data;
using System.Text.RegularExpressions;
using System.Data.SQLite;

namespace Cinchoo.Core.ETL
{
    public class ChoETLSQLiteConnectionJob : ChoETLTask
    {
        private string _connectionString;
        private bool _transactionScope;

        protected IDbConnection _connection;
        protected IDbTransaction _trans;

        #region Constructors

        public ChoETLSQLiteConnectionJob(string connectionString, bool transactionScope)
        {
            _connectionString = connectionString;
            _transactionScope = transactionScope;
        }

        #endregion Constructors

        protected override bool Initialize()
        {
            ChoGuard.ArgumentNotNullOrEmpty(_connectionString, "ConnectionString");

            _connection = new SQLiteConnection(_connectionString);
            _connection.Open();
            ETLRuntime.AddGlobalResource(_connectionString, _connection);

            if (_transactionScope)
            {
                _trans = _connection.BeginTransaction();
                ETLRuntime.AddGlobalResource("{0}_TRANS".FormatString(_connectionString), _trans);
            }

            return base.Initialize();
        }

        protected override void Commit()
        {
            if (_trans != null)
                _trans.Commit();
            _connection.Close();

            base.Commit();
        }

        protected override void Rollback()
        {
            if (_trans != null)
                _trans.Rollback();
            _connection.Close();

            base.Rollback();
        }
    }
}
